<template>
  <div class="app-container">
    <div class="item-head">
      <el-input
        v-model="listQuery.createUser"
        placeholder="请输入创建者姓名"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="getList"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">
        查找项目
      </el-button>
      <el-button
        class="head-create"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建项目
      </el-button>
    </div>

    <!--    标签-->
    <el-tabs v-model="active" @tab-click="handleClick">
      <!--      <el-tab-pane v-for="(it,index) in tabs" :key="index" :label="it" :name="index.toString()">-->
      <el-tab-pane label="项目信息">

        <!-- 主显示图 -->
        <div class="item-table">
          <el-table
            :key="tableKey"
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width:100%;min-width:800px;"
          >
            <el-table-column label="项目名" prop="name" align="center" />
            <el-table-column label="项目描述" prop="summary" align="center" />
            <el-table-column label="创建时间" prop="createTime" align="center" />
            <el-table-column label="修改时间" align="center">
              <template slot-scope="{row}">
                {{ row.updateTime || 'null' }}
              </template>
            </el-table-column>

            <!--        和tab绑定-->
            <el-table-column label="操作" align="center" min-width="130" class-name="small-padding fixed-width">
              <template slot-scope="{row}">
                <el-button type="primary" size="mini" @click="handleCheck(row)">
                  项目实例
                </el-button>
                <el-button type="primary" size="mini" @click="handleUpdate(row)">
                  编辑
                </el-button>
                <el-button type="danger" size="mini" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 底部分页组件 -->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>

      <!-- 项目实例 -->
      <el-tab-pane label="项目实例">
        <div class="dialog-view">
          <!--      <el-dialog v-if="dialogStatus=='check'" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">-->
          <el-form :model="projectData" style="max-height:600px;overflow-y:auto;">
            <el-form-item label="项目名：">
              {{ projectData.name }}
            </el-form-item>
            <el-form-item label="项目描述：">
              {{ projectData.summary }}
            </el-form-item>
            <el-form-item label="创建时间：">
              {{ projectData.createTime }}
            </el-form-item>
            <el-form-item label="模板名：">
              {{ projectData.modelVo.name }}
            </el-form-item>

            <el-form-item label="检查项：">
              <el-table
                v-loading="optionDatasLoading"
                :data="optionDatas"
                border
                fit
                highlight-current-row
                style="width:100%"
              >
                <el-table-column label="ID" prop="id" align="center" />
                <el-table-column label="组名" prop="group" align="center" />
                <el-table-column label="检查项" prop="name" align="center" />
                <el-table-column label="检查结果" prop="value" align="center" />
              </el-table>
            </el-form-item>

            <el-form-item label="测试项：">
              <el-table
                :data="projectData.tableOptions"
                border
                fit
                highlight-current-row
                style="width:100%"
              >
                <el-table-column
                  v-for="(item ,index) in projectData.modelVo.tableOptions"
                  :key="index"
                  :prop="item.id"
                  :label="item.name"
                />
                <el-table-column label="操作" align="center" min-width="100" class-name="small-padding fixed-width">
                  <template slot-scope="{row}">
                    <el-button type="primary" size="mini" @click="handleUpdateExample2(row)">
                      编辑
                    </el-button>
                    <el-button type="danger" size="mini" @click="handleDeleteExample2(row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <line-chart :width="'900px'" :height="'450px'" :chart-data="lineChartData" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleUpdateExample1">设置检查项</el-button>
            <el-button type="primary" @click="handleCreateExample2">新增测试项</el-button>
            <el-button @click="dialogFormVisible=false">关闭</el-button>
          </div>
          <!--      </el-dialog>-->
        </div>

      </el-tab-pane>

      <!-- 创建/修改项目 -->
      <el-dialog
        v-if="dialogStatus==='create'"
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <el-form ref="projectData" :rules="projectDataRules" :model="projectData">
          <el-form-item v-show="dialogStatus==='create'" label="模板：" prop="modelId">
            <el-select v-model="projectData.modelId" placeholder="请选择模板">
              <el-option
                v-for="item in templateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="dialogStatus==='update'" label="模板：">
            {{ projectData.modelVo.name }}
          </el-form-item>
          <el-form-item label="项目名：" prop="name">
            <el-input v-model="projectData.name" />
          </el-form-item>
          <el-form-item label="项目描述：" prop="summary">
            <el-input v-model="projectData.summary" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="createProject()">提交</el-button>
          <!--        <el-button type="primary" @click="updateProject()">提交</el-button>-->
          <el-button @click="dialogFormVisible=false">取消</el-button>
        </div>
      </el-dialog>

      <el-tab-pane label="编辑">
        <!--    <el-dialog-->
        <!--      v-if="dialogStatus==='update'||dialogStatus==='create'"-->
        <!--      :title="textMap[dialogStatus]"-->
        <!--      :visible.sync="dialogFormVisible"-->
        <!--      :close-on-click-modal="false"-->
        <!--    >-->
        <el-form ref="projectData" :rules="projectDataRules" :model="projectData">
          <el-form-item v-show="dialogStatus==='create'" label="模板：" prop="modelId">
            <el-select v-model="projectData.modelId" placeholder="请选择模板">
              <el-option
                v-for="item in templateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="dialogStatus==='update'" label="模板：">
            {{ projectData.modelVo.name }}
          </el-form-item>
          <el-form-item label="项目名：" prop="name">
            <el-input v-model="projectData.name" />
          </el-form-item>
          <el-form-item label="项目描述：" prop="summary">
            <el-input v-model="projectData.summary" />
          </el-form-item>
        </el-form>
        <!--        <div slot="footer" class="dialog-footer">-->
        <!--          <el-button type="primary" @click="dialogStatus==='create'?createProject():updateProject()">提交</el-button>-->
        <el-button type="primary" @click="updateProject()">提交</el-button>
        <el-button @click="dialogFormVisible=false">取消</el-button>
        <!--        </div>-->
        <!--    </el-dialog>-->

      </el-tab-pane>

    </el-tabs>

    <!-- 设置检查项 & 创建/修改测试项 -->
    <div class="dialog-view">
      <el-dialog
        v-if="dialogStatus==='updateE1'||dialogStatus==='updateE2'||dialogStatus==='createE2'"
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <el-form :model="exampleFrom" style="max-height:550px;overflow-y:auto;">
          <el-form-item
            v-for="item of exampleFrom.exampleValuelist"
            :key="item.id"
            :label="item.name"
          >
            <el-input v-model="item.value" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleOption">提交</el-button>
          <el-button @click="dialogStatus='check'">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { queryTemp, getDetail } from '@/api/template'
import {
  queryProjectList, queryProject, updateProject, deleteProject, createProject,
  createExample, updateExample, deleteExample
} from '@/api/project'
import LineChart from './components/LineChart'

export default {
  name: 'ProjectPage',
  components: { Pagination, LineChart },
  data() {
    return {
      listLoading: true,
      tableKey: 0,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 10,
        createUser: '',
        state: ''
      },

      active: 0,
      // tabs: ['项目信息', '项目实例', '编辑', '删除'],

      dialogStatus: '',
      textMap: {
        create: '新建项目',
        update: '修改项目',
        check: '项目实例',
        updateE1: '设置检查项',
        createE2: '新增项目实例',
        updateE2: '修改项目实例'
      },
      dialogFormVisible: false,

      list: [{
        id: '',
        name: '',
        summary: '',
        stateName: '',
        createTime: '',
        updateTime: ''
      }],
      projectData: {
        id: '',
        name: '',
        summary: '',
        stateName: '',
        createTime: '',
        updateTime: '',
        modelId: '',
        tableOptions: [],
        formOptions: '',
        modelVo: {
          id: '',
          name: '',
          description: '',
          createUserName: '',
          createUserImg: '',
          createTime: '',
          tableOptions: [{
            id: '',
            name: '',
            valueType: '',
            valueTypeName: ''
          }],
          options: [{
            id: '',
            group: '',
            name: '',
            remarks: '',
            valueType: 1,
            optionValuePoList: ['']
          }]
        }
      },

      optionDatas: [{
        id: '',
        group: '',
        name: '',
        value: ''
      }],
      optionDatasLoading: true,

      chartLoading: true,
      legendData: [],
      seriesData: [],
      xAxisData: [],
      lineChartData: {},

      exampleFrom: {
        projectId: '',
        type: '',
        exampleId: '',
        exampleValuelist: [{ optionId: '', name: '', value: '' }]
      },

      templateList: [{
        id: '',
        name: ''
      }],

      projectDataRules: {
        modelId: { required: true, trigger: 'blur' },
        name: { required: true, trigger: 'blur' },
        summary: { required: true, trigger: 'blur' }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {

    // 标签页切换
    handleClick(tab, event) {
      console.log(tab, event)
    },

    // 获取模板列表数据
    getTemplateList() {
      queryTemp({ state: 4 }).then(response => {
        if (response.resultCode === 200) {
          this.templateList = response.data
        }
      })
    },

    // 获取项目列表
    getList() {
      this.listLoading = true
      queryProjectList(this.listQuery).then(response => {
        if (response.resultCode === 200) {
          this.list = response.data.list
          this.total = response.data.count
          this.listLoading = false
        }
      })
      if (this.listLoading) {
        setTimeout(() => {
          this.listLoading = false
        }, 2000)
      }
    },
    // 获取项目数据
    getProjectDetail(id) {
      queryProject(id).then(response => {
        if (response.resultCode === 200) {
          this.projectData = Object.assign(response.data)
          this.projectData.tableOptions = response.data.tableOptions || []
          // this.projectData.id = response.data.id
          // this.projectData.name = response.data.name
          // this.projectData.summary = response.data.summary
          // this.projectData.createTime = response.data.createTime
          // this.projectData.updateTime = response.data.updateTime
          // this.projectData.modelId = response.data.modelId
          // this.projectData.formOptions = response.data.formOptions
          // this.projectData.modelVo = response.data.modelVo
        }
      })
    },

    // 新建项目
    handleCreate() {
      this.resetProjectData()
      this.getTemplateList()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createProject() {
      if (this.projectData.modelId == '') {
        this.$message.warning('请选择模板')
      } else if (this.projectData.name == '' || this.projectData.summary == '') {
        this.$message.warning('请输入必填项')
      } else {
        createProject(this.projectData).then(response => {
          if (response.resultCode === 200) {
            this.$message.success('创建项目成功')
            this.getList()
            this.dialogFormVisible = false
          }
        })
      }
    },

    // 修改项目
    handleUpdate(row) {
      var num = 2
      this.active = num.toString()

      this.dialogStatus = 'update'
      this.getTemplateList()
      this.getProjectDetail(row.id)
      this.dialogFormVisible = true
    },
    updateProject() {
      updateProject(this.projectData).then(response => {
        if (response.resultCode === 200) {
          this.$message.success('修改成功')
          this.getList()
          this.dialogFormVisible = false
        }
      })
    },

    // 删除项目
    handleDelete(row) {
      deleteProject(row.id).then(response => {
        if (response.resultCode === 200) {
          this.$message.success('删除成功')
          this.getList()
          this.dialogFormVisible = false
        }
      })
    },

    // 查看项目
    handleCheck(row) {
      const num = 1
      this.active = num.toString()

      this.optionDatasLoading = true
      this.optionDatas = []
      this.getProjectDetail(row.id)
      setTimeout(() => {
        for (let i = 0; i < this.projectData.modelVo.options.length; i++) {
          this.optionDatas.push({
            id: this.projectData.modelVo.options[i].id,
            group: this.projectData.modelVo.options[i].group,
            name: this.projectData.modelVo.options[i].name,
            value: this.projectData.formOptions[this.projectData.modelVo.options[i].id]
          })
          this.optionDatasLoading = false
        }
      }, 800)
      setTimeout(() => {
        const testData = []
        let datas = []
        for (let i = 0; i < this.projectData.modelVo.tableOptions.length; i++) {
          if (this.projectData.modelVo.tableOptions[i].valueType === 2) {
            datas = this.projectData.tableOptions.map(item => item[this.projectData.modelVo.tableOptions[i].id] || 0)
            testData.push({
              name: this.projectData.modelVo.tableOptions[i].name,
              datas: datas
            })
          }
        }
        this.legendData = testData.map(item => {
          return item.name
        })
        this.seriesData = testData.map(item => {
          return {
            name: item.name,
            type: 'line',
            smooth: true,
            animationDuration: 1000,
            data: item.datas
          }
        })
        this.xAxisData = []
        for (let i = 1; i <= this.projectData.tableOptions.length; i++) {
          this.xAxisData.push(i)
        }
        this.lineChartData = { legendData: this.legendData, seriesData: this.seriesData, xAxisData: this.xAxisData }
      }, 1200)
      this.dialogStatus = 'check'
      this.dialogFormVisible = true
    },

    handleOption() {
      if (this.dialogStatus == 'updateE1') {
        this.updateExample1()
      } else if (this.dialogStatus == 'createE2') {
        this.createExample2()
      } else if (this.dialogStatus == 'updateE2') {
        this.updateExample2()
      }
    },

    // 设置检查项
    handleUpdateExample1() {
      this.exampleFrom = {
        projectId: this.projectData.id,
        type: 1,
        exampleId: this.projectData.formOptions['id'],
        exampleValuelist: []
      }
      for (let i = 0; i < this.projectData.modelVo.options.length; i++) {
        this.exampleFrom.exampleValuelist.push({
          optionId: this.projectData.modelVo.options[i].id,
          name: this.projectData.modelVo.options[i].name,
          group: this.projectData.modelVo.options[i].group,
          value: this.projectData.formOptions[this.projectData.modelVo.options[i].id]
        })
      }
      this.dialogStatus = 'updateE1'
      this.dialogFormVisible = true
    },
    updateExample1() {
      updateExample(this.exampleFrom).then(response => {
        if (response.resultCode === 200) {
          this.dialogFormVisible = false
          this.$message.success('设置成功')
        }
      })
    },

    // 创建项目实例
    handleCreateExample2() {
      this.exampleFrom = {
        projectId: this.projectData.id,
        type: 2,
        exampleValuelist: []
      }
      for (let i = 0; i < this.projectData.modelVo.tableOptions.length; i++) {
        this.exampleFrom.exampleValuelist.push({
          optionId: this.projectData.modelVo.tableOptions[i].id,
          name: this.projectData.modelVo.tableOptions[i].name,
          value: ''
        })
      }
      this.dialogStatus = 'createE2'
      this.dialogFormVisible = true
    },
    createExample2() {
      createExample(this.exampleFrom).then(response => {
        if (response.resultCode === 200) {
          this.dialogFormVisible = false
          this.$message.success('新增成功')
        }
      })
    },

    // 修改项目实例
    handleUpdateExample2(row) {
      this.exampleFrom = {
        projectId: this.projectData.id,
        type: 2,
        exampleId: row.id,
        exampleValuelist: []
      }
      for (const item in row) {
        if (item != 'id') {
          this.exampleFrom.exampleValuelist.push({
            optionId: item,
            value: row[item],
            name: ''
          })
        }
      }
      for (let i = 0; i < this.projectData.modelVo.tableOptions.length; i++) {
        this.exampleFrom.exampleValuelist.map(it => {
          if (it.optionId == this.projectData.modelVo.tableOptions[i].id) {
            it.name = this.projectData.modelVo.tableOptions[i].name
          }
        })
      }
      this.dialogStatus = 'updateE2'
      this.dialogFormVisible = true
    },
    updateExample2() {
      updateExample(this.exampleFrom).then(response => {
        if (response.resultCode === 200) {
          this.dialogFormVisible = false
          this.$message.success('修改成功')
        }
      })
    },

    // 删除项目实例
    handleDeleteExample2(row) {
      deleteExample(row['id']).then(response => {
        if (response.resultCode === 200) {
          this.dialogFormVisible = false
          this.$message.success('删除成功')
        }
      })
    },

    // 重置项目数据
    resetProjectData() {
      this.projectData = {
        id: '',
        name: '',
        summary: '',
        stateName: '',
        createTime: '',
        updateTime: '',
        modelId: '',
        tableOptions: [],
        formOptions: '',
        modelVo: {
          id: '',
          name: '',
          description: '',
          createUserName: '',
          createUserImg: '',
          createTime: '',
          tableOptions: [{
            id: '',
            name: '',
            valueType: '',
            valueTypeName: ''
          }],
          options: [{
            id: '',
            group: '',
            name: '',
            remarks: '',
            valueType: 1,
            optionValuePoList: ['']
          }]
        }
      }
    }
  }
}
</script>

<style>
  .el-dialog__wrapper {
    min-width: 2000px;
  }

  .el-form-item__content {
    margin-right: 10%;
  }

  .el-radio {
    margin-top: 9px;
  }
</style>
